package com.emm.yixun.marketing.service.impl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.jws.WebService;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.emm.yixun.basic.service.AppPushService;
import com.emm.yixun.basic.service.DataPermissionService;
import com.emm.yixun.basic.service.ProjectService;
import com.emm.yixun.basic.service.SalesGroupService;
import com.emm.yixun.basic.service.SalesGroupUserService;
import com.emm.yixun.common.constant.SysConstants;
import com.emm.yixun.common.enums.DataAuthorityEnums;
import com.emm.yixun.common.exception.ResponseCode;
import com.emm.yixun.common.exception.XFUNExceptionCode;
import com.emm.yixun.common.model.Project;
import com.emm.yixun.common.model.SalesGroup;
import com.emm.yixun.common.model.SalesGroupUser;
import com.emm.yixun.common.model.dto.SalesGroupDto;
import com.emm.yixun.common.model.dto.SalesGroupUserDto;
import com.emm.yixun.common.model.dto.SalesGroupViewDto;
import com.emm.yixun.common.page.Page;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.marketing.service.SalesGroupServiceFacade;

@Service("salesGroupServiceFacade")
@WebService(name="com.emm.yixun.marketing.service.SalesGroupServiceFacade")
public class SalesGroupServiceFacadeImpl implements SalesGroupServiceFacade{
	private  final Logger   logger = LoggerFactory.getLogger(this.getClass()); 
	
	@Autowired
	private SalesGroupService service;
	
	@Autowired
	private SalesGroupUserService userService;
	
	@Autowired
	private DataPermissionService dataPermissionService;
	
	@Autowired
	private SalesGroupUserService salesGroupUserService;
	
	@Autowired
	private AppPushService appPushService;
	
	@Autowired
	private ProjectService projectService;

	@Override
	public Response<SalesGroupDto> save(SalesGroupDto dto) {
		Response<SalesGroupDto> response=new Response<SalesGroupDto>();
		try {
			if(null==dto){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("保存"));
				return response;
			}
			SalesGroupDto mDto=service.create(dto);
			if(null==mDto){
				response.fail("80000", "保存数据错误");
				return response;
			}
			response.success(mDto);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("保存数据错误：{}",e);
		}
		return response;
	}

	@Override
	public Response<Integer> updateByPrimaryKey(SalesGroupDto dto,Boolean selective) {
		Response<Integer> response=new Response<Integer>();
		try {
			if(null==selective || null==dto || null==dto.getId()){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("更新"));
				return response;
			}
			
			if(selective){
				int count=service.update(dto);
				if(count>0){
					response.success(Integer.valueOf(count));
				}else{
					response.fail("90001", "更新数据失败");
				}
			}else{
				response.fail("90000", "暂未实现,修改参数selective=true即可");
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("更新数据错误：{}",e);
		}
		return response;
	}

	@Override
	public Response<Integer> deleteByPrimaryKey(Long id) {
		Response<Integer> response=new Response<Integer>();
		try {
			if(null==id){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("删除"));
				return response;
			}
			SalesGroupDto mDto=new SalesGroupDto();
			mDto.setId(id);
			int count=service.destroy(mDto);
			if(count>0){
				//删除子表数据
				SalesGroupUserDto entity = new SalesGroupUserDto();
				entity.setSalesGroupId(id);
				userService.destroy(entity);
				response.success(Integer.valueOf(count));
			}else{
				response.fail("90001", "删除数据失败");
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("删除数据错误：{}",e);
		}
		return response;
	}
	
    @Override
	public Response<SalesGroup> findById(Long id) {
		Response<SalesGroup> response=new Response<SalesGroup>();
		try {
			if(null==id){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("主键查询"));
				return response;
			}
			SalesGroup entity=service.selectById(id);
			if(null==entity){
				response.fail("90001", "主键查询数据失败");
			}else{
				response.success(entity);;
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("主键查询数据错误：{}",e);
		}
		return response;
	}

	@Override
	public ResponseList<SalesGroup> findByDto(SalesGroupDto dto) {
		ResponseList<SalesGroup> response=new ResponseList<SalesGroup>();
		try {
			if(null==dto){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("查询"));
				return response;
			}
			List<SalesGroup> list=service.selectListByDto(dto);
			if(null==list){
				response.fail(ResponseCode.NO_DATA_FOUND.getCode(), ResponseCode.NO_DATA_FOUND.formatMessage("查询"));
				return response;
			}
			response.success(list);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询数据错误：{}",e);
		}
		return response;
	}

	@Override
	public Page<SalesGroup> findPageByDto(SalesGroupDto dto, Integer begin,Integer row) {
		Page<SalesGroup> response=new Page<SalesGroup>();
		try {
			if(null==dto || null==begin || null==row){
				response.setSuccess(false);
				response.setErrorMsg("参数不合法");
				return response;
			}
			Page<SalesGroup> page = service.getPageModel(dto, begin, row);
			if(null==page.getRows()){
				response.setSuccess(false);
				response.setErrorMsg("分页数据不存在");
				return response;
			}
			response=page;
			response.setSuccess(true);
		} catch (Exception e) {
			response.setSuccess(false);
			response.setErrorMsg(ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询分页数据错误：{}",e);
		}
		return response;
	}

	@Override
	public Page<SalesGroupViewDto> groupListPage(SalesGroupDto dto, Integer begin,Integer row) {
		Page<SalesGroupViewDto> response=new Page<SalesGroupViewDto>();
		try {
			if(null==dto || null==begin || null==row){
				response.setSuccess(false);
				response.setErrorMsg("参数不合法");
				return response;
			}
			//数据权限
			if(SysConstants.openDataPermission){
				String dataPermission = dataPermissionService.dataPermissionCondition(dto.getPermissionUserId(), dto.getResourcesCode(), dto.getPrefix(), dto.getColumnName());
				String [] dataPermissionArr = dataPermission.split(":");
				if("00".equals(dataPermissionArr[0])){
					response.setErrorMsg(XFUNExceptionCode.USER_PRODUCTNOEXIST.getDesin());
					response.setSuccess(false);
					return response;
				}
				dto.setDataPermission(dataPermissionArr[1]);
			}
			
			Page<SalesGroupViewDto> page = service.groupList(dto, begin, row);
			if(null==page.getRows()){
				response.setSuccess(false);
				response.setErrorMsg("分页数据不存在");
				return response;
			}
			response=page;
			response.setSuccess(true);
		} catch (Exception e) {
			response.setSuccess(false);
			response.setErrorMsg(ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询分页数据错误：{}",e);
		}
		return response;
	}

	@Override
	public Response<Boolean> closeGroup(Long id) {
		Response<Boolean> response=new Response<Boolean>();
		try {
			if(id==null){
				response.setSuccess(false);
				response.setResultMessage("参数不合法");
				return response;
			}
			SalesGroupDto entity = new SalesGroupDto();
			entity.setId(id);
			entity.setStatus("1");
			int row = service.update(entity);
			if(row>0){
				SalesGroupUserDto dto = new SalesGroupUserDto();
				dto.setSalesGroupId(id);
				List<SalesGroupUser> user = userService.selectListByDto(dto);
				for (SalesGroupUser list:user) {
					SalesGroupUserDto userDto = new SalesGroupUserDto();
					userDto.setId(list.getId());
					userDto.setStatus("1");
					userService.update(userDto);
					
					//用户所在项目组变更
					SalesGroup salesGroupEntity = service.selectById(id);
					Map<String, String> jsonMap = new HashMap<String, String>();
					jsonMap.put("name", "项目组变更");
					jsonMap.put("projectId", String.valueOf(salesGroupEntity.getProjectId()));//项目Id
					Project projectEntity = projectService.selectById(salesGroupEntity.getProjectId());
					jsonMap.put("projectName", projectEntity.getProjectName());//项目名称
					jsonMap.put("pushStatus", "1");//状态：0 正常，1 已关闭
					JSONObject jsonObject = (JSONObject) JSONObject.toJSON(jsonMap);
					String json = jsonObject.toString();
					Map<String, String> map = new HashMap<String, String>();
					map.put("Data", json);
					map.put("pushType", "xmzbg");//项目组变更推送固定类型值
					//接收push消息
					String text = "您所在的项目组：["+salesGroupEntity.getName()+"]，发生变更";
					appPushService.pushMessage(String.valueOf(list.getUserId()), text, null, map);//用户所在项目组数据变动
				}
			}
			response.setSuccess(true);
			return response;
		} catch (Exception e) {
			response.setSuccess(false);
			logger.error("关闭项目组异常:{}",e);
		}
		return response;
	}
	
	public ResponseList<SalesGroup> findAssignedSalesGroupByDto(SalesGroupDto dto) {
		ResponseList<SalesGroup> response=new ResponseList<SalesGroup>();
		try {
			if(null==dto){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("查询"));
				return response;
			}
			if(StringUtils.isNotBlank(dto.getResourcesCode())){
				String roleDataAuthorityValue=dataPermissionService.roleDataAuthorityValue(dto.getPermissionUserId(), dto.getResourcesCode());
				//查询用户所在销售组
				Map<Long, Long> sgMap = new HashMap<Long, Long>();
				SalesGroupUserDto salesGroupUserDto = new SalesGroupUserDto();
				salesGroupUserDto.setUserId(dto.getPermissionUserId());
				salesGroupUserDto.setStatus("0");
				List<SalesGroupUser> salesGroupUserList = salesGroupUserService.selectListByDto(salesGroupUserDto);
				// 销售组Map
				for (SalesGroupUser salesGroupUser : salesGroupUserList) {
					sgMap.put(salesGroupUser.getSalesGroupId(),salesGroupUser.getSalesGroupId());
				}
				if(roleDataAuthorityValue.equals(DataAuthorityEnums.DATA_AUTHORITY_04.getNo()) || roleDataAuthorityValue.equals(DataAuthorityEnums.DATA_AUTHORITY_01.getNo())){
					//销售组
					String dataPermission=buildSgCondition(sgMap,"t","id");
					dto.setDataPermission(dataPermission);
				}else if(roleDataAuthorityValue.equals(DataAuthorityEnums.DATA_AUTHORITY_00.getNo())){
					//无权限默认查不出销售组
					response.success(new ArrayList<SalesGroup>());
					return response;
				}else{
					//当是项目组或者全部默认取当前项目所有销售组
				}
			}
			List<SalesGroup> list=service.selectListByDto(dto);
			if(null==list){
				response.fail(ResponseCode.NO_DATA_FOUND.getCode(), ResponseCode.NO_DATA_FOUND.formatMessage("查询"));
				return response;
			}
			response.success(list);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询数据错误：{}",e);
		}
		return response;
	}
	
	public String buildSgCondition(Map<Long, Long> sgMap, String prefix, String columnName) {
		StringBuffer sb = new StringBuffer();
		sb.append(" AND (");
		Iterator<Map.Entry<Long, Long>> it = sgMap.entrySet().iterator();
		while (it.hasNext()) {
			Map.Entry<Long, Long> entry = it.next();
			// 销售组,value值为产品编码 projectCode
			Long value = entry.getValue();
			sb.append(prefix + "." + columnName + " = " + value + "");
			if (it.hasNext()) {
				sb.append(" or ");
			}
		}
		sb.append(")");
		return sb.toString();
	}

}
